import * as PIXI from 'pixi.js'
import { nameFont } from '@/utils/setting'
import { watch } from 'vue'
import { setPixi, getPixi, getPixiData } from '@/store/modules/usePixiStore'
import useMainStore from '@/store/modules/useMainStore'
import useSearchStore from '@/store/modules/useSearchStore'
import useModalStore from '@/store/modules/useModalStore'
import useDiyStore from '@/store/modules/useDiyStore'
import Card from '@/views/Main/Card'
import { useWindowSize } from '@vueuse/core'
import { bottomParams, diyParams } from './params'
import { gsap } from 'gsap'
import { diyTypeClick, diyRankClick, diyCategoryClick, diyElementClick, diySeriesClick } from './indiv'
import { CATEGORY } from '@/config'
import { skillConsumeModule } from '@/utils/bundle'
import dayjs from 'dayjs'

const mainStore = useMainStore()
const searchStore = useSearchStore()
const modalStore = useModalStore()
const diyStore = useDiyStore()
const { height } = useWindowSize()
const { scale } = mainStore.getAppAttr
// 监听当前页数, 滚动卡册
watch(
  () => searchStore.current,
  val => {
    const cardSetsContainer = getPixi('cardSets')
    const bottomHeight = height.value / scale - 114 - 30
    bottomParams.quiet = false
    gsap.to(cardSetsContainer.position, {
      duration: 0.7,
      y: -(val - 1) * bottomHeight,
      onComplete: () => {
        bottomParams.quiet = true
      },
    })
  },
)
// 监听卡册切换数据源
watch(
  () => searchStore.from,
  val => {
    const illBtn = getPixi('illBtn')
    const creation = getPixi('creation')
    if (val === 'cards') {
      illBtn.visible = true
      creation.visible = false
    } else if (val === 'diys') {
      illBtn.visible = false
      creation.visible = true
    }
    Card()
  },
)
// 监听模态框状态
watch(
  () => modalStore.visible,
  val => {
    const modalContainer = getPixi('modal')
    modalContainer.visible = val
  },
)
watch(
  () => diyStore.visible,
  val => {
    const diyContainer = getPixi('diyModal')
    diyContainer.visible = val
  },
)
// 监听DIY种类选项
watch(
  () => diyStore.creationData.type,
  val => {
    // 影响攻击血量的显示
    getPixi(diyStore.uidMap.atk)!.visible = val === '生灵'
    getPixi(diyStore.uidMap.hp)!.visible = val === '生灵'
    const uidArr = diyTypeClick.whiteList
    uidArr.forEach(uid => {
      const pixiData = getPixiData(uid)
      const selectionType = getPixi(uid).children[1]
      selectionType.visible = pixiData.key === val
      // 映射到右侧
      const rightTypeContainer = getPixi(pixiData.rightType)
      rightTypeContainer.visible = pixiData.key === val
      // 种类变化引起类别变化
      const categoryContainer = getPixi(pixiData.category)
      categoryContainer.visible = pixiData.key === val
      // 重置选项
      if (pixiData.key === val) {
        diyStore.creationData.category = Object.keys(CATEGORY[pixiData.key as keyof typeof CATEGORY])[0]
      }
    })
  },
)

// 监听DIY类别选项
watch(
  () => diyStore.creationData.category,
  val => {
    const uidArr = diyCategoryClick.whiteList
    uidArr.forEach(uid => {
      const pixiData = getPixiData(uid)
      const selectionType = getPixi(uid).children[1]
      selectionType.visible = pixiData.key === val
      // 映射到右侧
      const rightCategoryContainer = getPixi(pixiData.rightCategory)
      rightCategoryContainer.visible = pixiData.key === val
    })
  },
)
// 监听DIY元素选项
watch(
  () => diyStore.creationData.element,
  val => {
    const uidArr = diyElementClick.whiteList
    uidArr.forEach(uid => {
      const pixiData = getPixiData(uid)
      const selectionType = getPixi(uid).children[1]
      selectionType.visible = pixiData.key === val
      // 映射到右侧
      const rightElementContainer = getPixi(pixiData.rightElement)
      rightElementContainer.visible = pixiData.key === val
    })
  },
)
// 监听DIY品阶选项
watch(
  () => diyStore.creationData.rank,
  val => {
    const uidArr = diyRankClick.whiteList
    uidArr.forEach(uid => {
      const pixiData = getPixiData(uid)
      const selectionType = getPixi(uid).children[1]
      selectionType.visible = pixiData.key === val
      // 映射到右侧
      const rightSeriesContainer = getPixi(pixiData['rightSeries_' + diyStore.creationData.series])
      rightSeriesContainer.visible = pixiData.key === val
    })
  },
)

// 监听DIY系列选项
watch(
  () => diyStore.creationData.series,
  val => {
    const uidArr = diySeriesClick.whiteList
    uidArr.forEach(uid => {
      const pixiData = getPixiData(uid)
      const selectionType = getPixi(uid).children[1]
      selectionType.visible = pixiData.key === val
      // 映射到右侧
      const rightSeriesContainer = getPixi(pixiData['rightSeries_' + diyStore.creationData.rank])
      rightSeriesContainer.visible = pixiData.key === val
    })
  },
)
// 监听DIY攻击文本
watch(
  () => diyStore.creationData.atk,
  val => {
    const uid = diyStore.uidMap.atk
    const text = getPixi(uid) as PIXI.Text
    if (!text) {
      return
    }
    text.text = val
  },
)
// 监听DIY生命文本
watch(
  () => diyStore.creationData.hp,
  val => {
    const uid = diyStore.uidMap.hp
    const text = getPixi(uid) as PIXI.Text
    if (!text) {
      return
    }
    text.text = val
  },
)
// 监听DIY消耗文本
watch(
  () => diyStore.creationData.consume,
  val => {
    const uid = diyStore.uidMap.consume
    const text = getPixi(uid) as PIXI.Text
    if (!text) {
      return
    }
    text.text = val
  },
)
// 监听DIY名称文本
watch(
  () => diyStore.creationData.name as string,
  val => {
    const uid = diyStore.uidMap.name
    const container = getPixi(uid) as PIXI.Container
    if (!container) {
      return
    }
    container.removeChildren()
    const nameArr = val.split('')
    const nameSetting = nameFont(nameArr.length)
    val.split('').forEach((item, index) => {
      const text = new PIXI.Text({
        text: item,
        alpha: 0.8,
        style: {
          fontFamily: 'RZFont',
          fontSize: nameSetting.fontSize,
          fill: 0xffffff,
          align: 'center',
          dropShadow: {
            alpha: 0.55,
            distance: 3,
          },
        },
      })
      text.anchor.set(0.5)
      text.position.set(0, 30 - 256 / 2 + nameSetting.startY + index * nameSetting.lineSize)
      container.addChild(text)
    })
  },
)
// 监听DIY能力文本
watch([() => diyStore.creationData.ability as string, () => diyStore.creationData.param.abilityFontSize as number], async ([val, size]) => {
  const uid = diyStore.uidMap.ability
  const container = getPixi(uid) as PIXI.Container
  if (!container) {
    return
  }
  container.removeChildren()
  // 创建文本对象
  const text = new PIXI.Text({
    text: val,
    alpha: 0.9,
    style: {
      fontFamily: 'XQFont',
      fontSize: size,
      fill: 0xffffff,
      align: 'center',
      lineHeight: size,
    },
  })
  text.anchor.set(0.5)
  container.addChild(text)
  // 文本有多少行
  const rowNum = val.split('').filter(char => char === '\n').length
  const pattern = /\{\{TP(\d+|\?)\}\}/
  const match = val.match(pattern) as Array<string>
  if (match) {
    let skillConsume = match[1] as Wx.Card.SKILL_CONSUME
    if (skillConsume === '?' || Number(skillConsume) > 8) {
      skillConsume = '?'
    }
    const point = { x: 0, y: 0 }
    const newText = val.replace(match[0], (r, i) => {
      // 图标之前后多少个换行符, 即图标所在行的下标
      const beforeRowNum = val
        .substring(0, i)
        .split('')
        .filter(char => char === '\n').length
      // 所在行的内容
      const rowStr = val.split('\n')[beforeRowNum]
      // 所在行的图标之后的内容
      const afterRowStr = val.substring(i).split('\n')[0]
      // 计算文本宽度
      const tempText = new PIXI.Text({
        text: rowStr,
        style: { fontSize: size },
      })
      const temp2Text = new PIXI.Text({
        text: afterRowStr,
        style: { fontSize: size },
      })
      const place = '     '
      const temp3Text = new PIXI.Text({
        text: place,
        style: { fontSize: size },
      })
      point.x = tempText.width / 2 - temp2Text.width + temp3Text.width
      point.y = beforeRowNum - rowNum / 2
      return place
    })
    const sprite = await skillConsumeModule({ skillConsume })
    sprite.anchor.set(0.5)
    sprite.scale.set((size / 28) * 0.64)
    sprite.position.set(point.x, point.y * sprite.height)
    text.text = newText
    container.addChild(sprite) // 文字的中轴在文字区域的中间部分
  }
})

watch(
  () => diyStore.creationData.param.abilityFontSize as number,
  val => {
    const sprite = getPixi(diyStore.abilityFontSizeUid) as PIXI.Text
    sprite.text = val
  },
)

// 监听DIY图片选择
watch(
  () => diyStore.creationData.picture as string,
  async val => {
    const container = getPixi(diyStore.imageUid)
    container.removeChildren()
    if (val === '') {
      return
    }
    const id = dayjs().unix()
    await PIXI.Assets.load({ alias: String(id), src: val })
    const sprite = PIXI.Sprite.from(String(id)) // 创建精灵
    sprite.anchor.set(0.5)
    if (diyStore.improtData) {
      sprite.scale.set(diyStore.creationData.transform.scale)
      sprite.position.set(diyStore.creationData.transform.x, diyStore.creationData.transform.y)
    } else {
      // 存放真实宽高
      diyStore.creationData.transform.realWidth = sprite.width
      diyStore.creationData.transform.realHeight = sprite.height
      diyStore.creationData.transform.minScale = Math.max(292 / sprite.width, 292 / sprite.height) // 最小缩放倍数
      diyStore.creationData.transform.scale = diyStore.creationData.transform.minScale
      diyStore.creationData.transform.x = 0
      diyStore.creationData.transform.y = 0
      sprite.scale.set(diyStore.creationData.transform.minScale)
    }
    diyStore.improtData = false
    container.addChild(sprite)
    setPixi(sprite.uid, sprite)
    // PIXI.Assets.unload(diyParams.alias) //清空旧的信息
    diyParams.alias = id // 暂存一下
    diyStore.creationData.id = id
  },
)

// 监听DIY数据ID
// watch(
//   () => diyStore.creationData.id,
//   () => {
//     diyStore.improtData = true
//   },
// )
